/*
 * @Descripttion: 侧边栏菜单组件
 * @Author: lhl
 * @Date: 2024-11-18
 */
import { Menu } from 'antd';
import type { MenuProps } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
import { useEffect, useState } from 'react';
import Icon from '@/components/Icon';
import API from '@/api';

// 菜单项类型定义
interface MenuItemType {
  path: string;
  meta: {
    title: string;
    icon?: string;
    hidden?: boolean;
  };
  children?: MenuItemType[];
}

// localStorage 键名常量
const STORAGE_KEYS = {
  SELECTED: 'selectedMenuKeys',
  OPEN: 'openMenuKeys',
} as const;

const SideMenu = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [menuList, setMenuList] = useState<MenuItemType[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<string[]>(() => {
    const savedKeys = localStorage.getItem(STORAGE_KEYS.SELECTED);
    return savedKeys ? JSON.parse(savedKeys) : [location.pathname];
  });

  const [openKeys, setOpenKeys] = useState<string[]>(() => {
    const savedOpenKeys = localStorage.getItem(STORAGE_KEYS.OPEN);
    return savedOpenKeys ? JSON.parse(savedOpenKeys) : [];
  });

  // 获取当前路径的所有父级路径
  const getParentPaths = (path: string): string[] => {
    const pathArray = path.split('/').filter(Boolean);
    const paths: string[] = [];
    let currentPath = '';

    pathArray.forEach((segment, index) => {
      if (index === pathArray.length - 1) return;
      currentPath += `/${segment}`;
      paths.push(currentPath);
    });

    return paths;
  };

  // 获取菜单数据
  useEffect(() => {
    const fetchMenuData = async () => {
      try {
        const data = await API.user.menuData();
        setMenuList(data);
      } catch (error) {
        console.error('Failed to fetch menu data:', error);
      }
    };
    fetchMenuData();
  }, []);

  // 监听路由变化，更新菜单状态
  useEffect(() => {
    const currentPath = location.pathname;
    const parentPaths = getParentPaths(currentPath);

    setSelectedKeys([currentPath]);
    setOpenKeys(parentPaths);

    localStorage.setItem(STORAGE_KEYS.SELECTED, JSON.stringify([currentPath]));
    localStorage.setItem(STORAGE_KEYS.OPEN, JSON.stringify(parentPaths));
  }, [location.pathname]);

  // 将菜单数据转换为 antd Menu 组件所需的格式
  const getMenuItems = (menuData: MenuItemType[], parentPath = ''): MenuProps['items'] => {
    return menuData
      .map((item) => {
        if (item.meta?.hidden) return null;

        const fullPath = item.path.startsWith('/') ? item.path : `${parentPath}/${item.path}`;
        const menuItem: any = {
          key: fullPath,
          icon: item.meta.icon ? <Icon name={item.meta.icon} /> : null,
          label: item.meta.title,
        };

        // 处理外部链接
        if (item.path.startsWith('http')) {
          menuItem.label = (
            <a href={item.path} target="_blank" rel="noopener noreferrer">
              {item.meta.title}
            </a>
          );
        }

        // 处理子菜单
        if (item.children?.length) {
          const visibleChildren = item.children.filter((child) => !child.meta?.hidden);
          if (visibleChildren.length) {
            menuItem.children = getMenuItems(visibleChildren, fullPath);
          }
        }

        return menuItem;
      })
      .filter(Boolean);
  };

  // 处理子菜单展开/收起
  const handleOpenChange: MenuProps['onOpenChange'] = (keys) => {
    setOpenKeys(keys);
    localStorage.setItem(STORAGE_KEYS.OPEN, JSON.stringify(keys));
  };

  // 处理菜单点击
  const handleMenuClick: MenuProps['onClick'] = ({ key }) => {
    if (key.startsWith('http')) {
      window.open(key, '_blank');
      return;
    }
    navigate(key);
  };

  return (
    <Menu
      mode="inline"
      theme="dark"
      openKeys={openKeys}
      onOpenChange={handleOpenChange}
      selectedKeys={selectedKeys}
      items={getMenuItems(menuList)}
      onClick={handleMenuClick}
    />
  );
};

export default SideMenu;
